from telnetlib import EC

from selenium import webdriver
import time

from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
# By类，用于定位元素
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# driver = webdriver.Chrome()
S = Service("D:/chromedriver/chromedriver-win64/chromedriver.exe")
driver = webdriver.Chrome(service=S)
try:
    base_url = 'https://passport.csdn.net/login?code=applets'
    time.sleep(3)
    # 隐式等待
    driver.implicitly_wait(5)
    driver.get(base_url)
    # 显示等待：等待登录元素加载
    wait = WebDriverWait(driver, 5)
    loginElement = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/div/div[2]/div[2]/div[3]/div/div/span[2]')))
    loginElement.click()
    time.sleep(1)
    # 找到用户名输入框
    userInput = driver.find_element(By.XPATH, '/html/body/div/div/div/div[2]/div[2]/div/div[2]/div[1]/div[1]/div/input')
    userInput.click()
    userInput.send_keys("18287521484")
    time.sleep(1)
    # 找到密码输入框
    passwordInput = driver.find_element(By.XPATH,
                                        '/html/body/div/div/div/div[2]/div[2]/div/div[2]/div[1]/div[2]/div/input')
    passwordInput.click()
    passwordInput.send_keys("zxj12345678")
    # 找到登录按钮
    login = driver.find_element(By.XPATH, '/html/body/div/div/div/div[2]/div[2]/div/div[2]/div[1]/div[4]/button')
    login.click()
    print("登录成功")

except Exception as error:
    print(f"发生了错误{error}")
finally:
    time.sleep(5)
    driver.quit()  # 关闭浏览器